package com.fy.service.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.fy.common.dto.UserBlackListPullDto;
import com.fy.common.entity.SkImChatSession;
import com.fy.common.entity.SkImUserBacklist;
import com.fy.common.entity.SkImUserFriends;
import com.fy.common.enums.SkImCommonStatusEnum;
import com.fy.common.enums.SkImUserRelationshipEnum;
import com.fy.common.model.PageRequest;
import com.fy.common.util.ImUtil;
import com.fy.common.util.TokenUtil;
import com.fy.dao.mapper.SkImUserBacklistMapper;
import com.fy.framework.common.model.R;
import com.fy.framework.component.config.LocaleMessage;
import com.fy.framework.component.config.RedissonComponet;
import com.fy.service.service.SkImChatSessionService;
import com.fy.service.service.SkImUserBacklistService;
import com.fy.service.service.SkImUserFriendsService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Optional;

import static com.fy.common.constant.RedisKeyConstant.USER_CHAT_SESSION;

/**
 * @author zhshuo
 * @date 2021/12/02 11:38
 **/
@Slf4j
@Service
public class SkImUserBacklistServiceImpl extends ServiceImpl<SkImUserBacklistMapper, SkImUserBacklist> implements SkImUserBacklistService {

    LocaleMessage localeMessage;

    RedissonComponet redissonComponet;

    SkImUserFriendsService userFriendsService;

    SkImChatSessionService chatSessionService;

    @Override
    public R<?> blackList(PageRequest<SkImUserBacklist> pageRequest) {
        Page<SkImUserBacklist> userBacklistPage = pageRequest.setRecords(
            baseMapper.blackList(pageRequest, pageRequest.getQueryParam().setSkImUserId(TokenUtil.getUserId())));
        return R.success(userBacklistPage);
    }

    @Override
    public R<?> pullBlackList(UserBlackListPullDto userBlackListPullDto) {
        Long blackUserId = userBlackListPullDto.getBlackUserId();
        Long userId = TokenUtil.getUserId();
        SkImUserFriends userFriends = userFriendsService.selectOne(new EntityWrapper<SkImUserFriends>().eq("sk_im_user_id", userId)
                .eq("target_user_id", userBlackListPullDto.getBlackUserId()));
        SkImUserBacklist userBacklist = new SkImUserBacklist().setSkImUserId(userId).setSkImBlackUserId(blackUserId);
        if(Objects.nonNull(userFriends)){
            userBacklist.setPreBlackRelation(SkImUserRelationshipEnum.FRIEND.getType());
            userFriendsService.update(new SkImUserFriends().setStatus(SkImUserRelationshipEnum.BLACK.getType()),
                    new EntityWrapper<SkImUserFriends>().eq("sk_im_user_id",userId).eq("target_user_id",blackUserId));
            userFriendsService.update(new SkImUserFriends().setStatus(SkImUserRelationshipEnum.BLACK.getType()),
                    new EntityWrapper<SkImUserFriends>().eq("sk_im_user_id",blackUserId).eq("target_user_id",userId));
            chatSessionService.update(new SkImChatSession().setStatus(SkImCommonStatusEnum.BLACK_DISABLE.getStatus()),
                    new EntityWrapper<SkImChatSession>().eq("session_id",ImUtil.chatSessionIdGenFriend(userId,blackUserId)));
            chatSessionService.update(new SkImChatSession().setStatus(SkImCommonStatusEnum.BLACK_DISABLE.getStatus()),
                    new EntityWrapper<SkImChatSession>().eq("session_id",ImUtil.chatSessionIdGenFriend(blackUserId,userId)));
            Optional.ofNullable(redissonComponet.getMapValue(USER_CHAT_SESSION + userId, ImUtil.chatSessionIdGenFriend(userId, blackUserId))).ifPresent(obj-> redissonComponet.setMap(USER_CHAT_SESSION + userId, ImUtil.chatSessionIdGenFriend(userId, blackUserId),((SkImChatSession)obj).setStatus(SkImCommonStatusEnum.BLACK_DISABLE.getStatus())));
            Optional.ofNullable(redissonComponet.getMapValue(USER_CHAT_SESSION + blackUserId, ImUtil.chatSessionIdGenFriend(blackUserId, userId))).ifPresent(obj-> redissonComponet.setMap(USER_CHAT_SESSION + blackUserId, ImUtil.chatSessionIdGenFriend(blackUserId, userId),((SkImChatSession)obj).setStatus(SkImCommonStatusEnum.BLACK_DISABLE.getStatus())));
        }else{
            userBacklist.setPreBlackRelation(SkImUserRelationshipEnum.STRANGER.getType());
        }
        insert(userBacklist.setStatus(SkImCommonStatusEnum.NORAML.getStatus()));
        return R.success(localeMessage.getMessage("im.common.successful"));
    }

    @Override
    public R<?> cancel(JSONObject param) {
        Long blackId = param.getLong("blackId");
        SkImUserBacklist userBacklist = selectById(blackId);
        Long userId = userBacklist.getSkImUserId();
        Long blackUserId = userBacklist.getSkImBlackUserId();
        if (userBacklist.getPreBlackRelation().equals(SkImUserRelationshipEnum.FRIEND.getType())) {
            userFriendsService.update(new SkImUserFriends().setStatus(SkImUserRelationshipEnum.FRIEND.getType()),
                    new EntityWrapper<SkImUserFriends>().eq("sk_im_user_id",userId).eq("target_user_id",blackUserId));
            userFriendsService.update(new SkImUserFriends().setStatus(SkImUserRelationshipEnum.FRIEND.getType()),
                    new EntityWrapper<SkImUserFriends>().eq("sk_im_user_id",blackUserId).eq("target_user_id",userId));
            chatSessionService.update(new SkImChatSession().setStatus(SkImCommonStatusEnum.NORAML.getStatus()),
                    new EntityWrapper<SkImChatSession>().eq("session_id",ImUtil.chatSessionIdGenFriend(userId,blackUserId)));
            chatSessionService.update(new SkImChatSession().setStatus(SkImCommonStatusEnum.NORAML.getStatus()),
                    new EntityWrapper<SkImChatSession>().eq("session_id",ImUtil.chatSessionIdGenFriend(blackUserId,userId)));
            Optional.ofNullable(redissonComponet.getMapValue(USER_CHAT_SESSION + userId, ImUtil.chatSessionIdGenFriend(userId, blackUserId))).ifPresent(obj-> redissonComponet.setMap(USER_CHAT_SESSION + userId, ImUtil.chatSessionIdGenFriend(userId, blackUserId),((SkImChatSession)obj).setStatus(SkImCommonStatusEnum.NORAML.getStatus())));
            Optional.ofNullable(redissonComponet.getMapValue(USER_CHAT_SESSION + blackUserId, ImUtil.chatSessionIdGenFriend(blackUserId, userId))).ifPresent(obj-> redissonComponet.setMap(USER_CHAT_SESSION + blackUserId, ImUtil.chatSessionIdGenFriend(blackUserId, userId),((SkImChatSession)obj).setStatus(SkImCommonStatusEnum.NORAML.getStatus())));
        }
        updateById(userBacklist.setStatus(SkImCommonStatusEnum.DELETED.getStatus()));
        return R.success(localeMessage.getMessage("im.common.successful"));
    }

    @Autowired
    public void setLocaleMessage(LocaleMessage localeMessage) {
        this.localeMessage = localeMessage;
    }
    @Autowired
    public void setRedissonComponet(RedissonComponet redissonComponet) {
        this.redissonComponet = redissonComponet;
    }
    @Autowired
    public void setUserFriendsService(SkImUserFriendsService userFriendsService) {
        this.userFriendsService = userFriendsService;
    }
    @Autowired
    public void setChatSessionService(SkImChatSessionService chatSessionService) {
        this.chatSessionService = chatSessionService;
    }
}
